package com.crack.nga2.volley;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.crack.nga2.entity.UserInfo;
import com.crack.nga2.utils.DataUtil;
import com.crack.nga2.utils.GlobalConst;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息请求
 * Created by Administrator on 2016/1/6.
 */
public class UserInfoRequest extends Request<UserInfo> {
    private Response.Listener<UserInfo> listener;

    public UserInfoRequest(int method, String url, Response.ErrorListener errorListener, Response.Listener<UserInfo> listener) {
        super(method, url, errorListener);
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> headers = new HashMap<>();
        headers.put("Cookie", GlobalConst.Cookie);
        return headers;
    }

    @Override
    protected Response<UserInfo> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(response.data, "GBK");
            json = DataUtil.getData(json);
            Type type = new TypeToken<Map<Integer, UserInfo>>() {
            }.getType();
            Gson gson = new Gson();
            Map<Integer, UserInfo> data = gson.fromJson(json, type);
            UserInfo userInfo = data.get(0);
            return Response.success(userInfo, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e.getMessage()));
        }
    }

    @Override
    protected void deliverResponse(UserInfo response) {
        if (listener != null) {
            listener.onResponse(response);
        }
    }
}
